#! /usr/bin/python
# -*- coding: utf-8 -*-

from collections import defaultdict

def load(fname):
    # init
    # each dict entry is an en key, and a set of related fr words
    bigdict = defaultdict(set)
    try:
        f = open(fname)
    except IOError:
        print 'File not found! Empty dictionary is loaded.'
        return bigdict
        
    # process for everyline
    for line in f:
        if line[0] == '#': continue
        # split @ TAB to get en, fr words
        [en,fr] = line.split('\t')
        # split @ ';' to get individual words
        for enw in [x.strip() for x in en.split(';')]:
            for frw in [x.strip() for x in fr.split(';')]:
                bigdict[enw].add(frw)
    return bigdict

class iDict():
    def __init__(self, filename = ''):
        self._dict = load(filename)

    # add an entry to dict        
    def update(self, entry):
        # an entry is a dict e.g. {'en_word': set(['fr1','fr2'])}
        for i in entry: self._dict[i].update(entry[i])

    def __len__(self):
        return len(self._dict)

    def __str__(self):
        s = ''
        for en in sorted(self._dict.keys()):
            s += en + ':'
            for  fr in sorted(self._dict[en]):
                s+= ' ' + fr + ';'
            s = s.strip(';') + '\n'
        return s

if __name__ == '__main__':
    print iDict('omegawiki.txt')
    
